<?php
namespace app\common\service\WebSocket\SocketService; 

use app\Normal;
use app\BaseService;
use app\common\service\SystemConfigService\Channel\ChannelConfigService;
use app\model\BbcModel\HotWords;

class HotWordsSocketService extends BaseService
{
    public $socket_connector;

    public $fd;

    public $host;
    public $pageLimit      = 2000;
    public $percent_status = [
        '1' => '写入中',
        '2' => '完成',
        '3' => '异常错误',
    ];
    
    public function HotWordsExport($parameters = []) {
        ini_set('memory_limit', '3096M');
        $this->socket_connector = $parameters['socket'];
        $this->fd               = $parameters['fd'];
        $this->host             = $parameters['host'];
        $data                   = $parameters['requestData'];
        $where=[
            ['df','=',0]
        ];
        $total_count=HotWords::instance()
            ->where($where)
            ->count();
        $total_page  = ceil($total_count / $this->pageLimit);
        $importData  = [];
        for ($page = 0; $page < $total_page; $page++) {
            $list=HotWords::instance()
                ->where($where)
                ->order('id desc')
                ->limit($page * $this->pageLimit, $this->pageLimit)
                ->select()
                ->toArray();
            if ($list) {
                $tmpData = [];
                foreach ($list as $v) {
                    $tmpData[] = [
                        $v['words'],
                    ];
                }
                $importData = array_merge($importData, $tmpData);
            }

            if ($page == $total_page - 1) {
                $percent = 98.00; //预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }

            if ($this->socket_connector) {
                $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
                    'percent' => $percent,
                ]);
                $send = json_encode($send, JSON_UNESCAPED_UNICODE);
                $this->socket_connector->push($this->fd, $send);
            }
        }
        //数据准备完成开始写入excel本地数据
        $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
            'percent' => 99.00,
        ]);
        $send = json_encode($send, JSON_UNESCAPED_UNICODE);
        $this->socket_connector->push($this->fd, $send);

        $fileName     = "热词导出";
        $headArr      = $this->getColumns();
        $data         = $importData;
        $download_url = xlsxFileLocalStorage($headArr, $data, $fileName, $this->host);
        return Normal::returnWsStatus(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $download_url,
            'name'=>'热词导出'
        ]);
    }
     //excel头部
    public function getColumns() {
        return [
            '热词名称',
        ];
    }
    
    public function HotWordsImport($parameters) {
        $this->socket_connector = $parameters['socket'];
        $this->fd = $parameters['fd'];
        $this->host = $parameters['host'];
        ini_set('memory_limit', '3096M');
        //判断是否第一步
        $data = $parameters['requestData'];
        $data['cid']            = $parameters['_master_user']['cid'];
        //这里去获oss配置
        $oss = (new ChannelConfigService())->getConfigByCode(['cid'=>$data['cid'],'code'=>'ali_oss']);
        if($oss['code']!=200){
            $send = Normal::returnWsStatus(Normal::WS_ERROR, "oss未配置");
            $send = json_encode($send, JSON_UNESCAPED_UNICODE);            
            $this->socket_connector->push($this->fd, $send);
            return $send;
        }
        $xlsx = $oss['data']['url'] . '/' . $data['fileName'];
        //$xlsx = 'http://www.practice.com' . '/' . $data['fileName'];
        $string = explode('.', $data['fileName']);
        $ext = end($string);
        $content = file_get_contents($xlsx);//文件保存到本地
        $path = app()->getRootPath() . '/public/websocketservice/';
        $fileName = $path . date("YmdHis") . "." . $ext;
        file_put_contents($fileName, $content);
        //获取商品数据
        $XlsxData = ExcelImport($fileName, $ext,1);
        $headerdata=$XlsxData[1];
        unset($XlsxData[1]);
        $chunk_data = array_chunk($XlsxData, $this->pageLimit);
        $total_page = count($chunk_data);
        $error_data = [];
        $goodsdata  = [];
        if($XlsxData){
            HotWords::instance()->del(['cid'=>$data['cid']]);
        }
        for ($page = 0; $page < $total_page; $page++) {
            
            foreach ($chunk_data[$page] as $i) {
                if($i[0]){
                    $repwhere=[['words','=',$i[0]],['cid','=',$data['cid']]];
                    $rep= HotWords::instance()->info($repwhere);
                    if($rep){
                        $error=$i;
                        $error[]='重复';
                        $error_data[]=$error;
                    }else{
                        $add_data = [
                            'words' => $i[0],
                            'cd' => time(),
                            'cid' => $data['cid'],
                            'cb_id'=> 0
                        ];
                        $res = HotWords::instance()->add($add_data);
                        if(!$res){
                            $error=$i;
                            $error[]='写入失败';
                            $error_data[]=$error;
                        }
                    }
                }else{
                    $error=$i;
                    $error[]='有误';
                    $error_data[]=$error;
                }
            }
            if ($page == $total_page - 1) {
                $percent = 98.00;//预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }
            $send = Normal::returnWsStatus(Normal::WS_START, "进行中", ['download_url' => '',
                'msg' => '进行中',
                'percent' => $percent
            ]);
            $send = json_encode($send, JSON_UNESCAPED_UNICODE);
            $this->socket_connector->push($this->fd, $send);
        }
        
        //最后需要判断是否有错误数据
        if (!empty($error_data)) {
            //返回错误的表格
            $headArr = $headerdata;
            $headArr[] = '错误信息';
            $importFileName = "错误列表导出明细";
            $download_url = xlsxFileLocalStorage($headArr, $error_data, $importFileName, $this->host);
            return Normal::returnWsStatus(Normal::WS_END, "有错误数据", ['download_url' => $download_url,
                'msg' => "有错误数据",'name'=>'热词导入',
                'percent' => 100,]);
        }

        return Normal::returnWsStatus(Normal::WS_END, "保存成功", [
            'download_url' => '',
            'msg' => "保存成功",
            'name'=>'热词导入',
            'percent' => 100
        ]);
    }
}
